#include "stdafx.h"
#include "IndexBuffer.h"


CIndexBuffer::CIndexBuffer(uint length, bool dynamic)
: m_pIB(nullptr)
, m_pLockData(nullptr)
, m_length(length)
, m_bDynamic(dynamic)
{
	ulong usage = dynamic ? D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY : 0;

	HRESULT hr = g_pDevice->CreateIndexBuffer(length, usage, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_pIB, nullptr);
	assert(hr == D3D_OK);
}

CIndexBuffer::~CIndexBuffer()
{
	SAFE_RELEASE(m_pIB);
}

void*	CIndexBuffer::Lock(uint offset, uint size, EIndexBufferLockType lock_type)
{
	assert(offset + size <= m_length);

	uint flags = 0;
	switch (lock_type)
	{
	case eIBLock_Discard:
		assert(offset == 0 && (size == m_length || size == 0));	//	all buffer discarded
		flags = m_bDynamic ? D3DLOCK_DISCARD : 0;
		break;

	case eIBLock_NoOverwrite:
		assert(m_bDynamic);
		flags = D3DLOCK_NOOVERWRITE;
		break;

	case eIBLock_ReadOnly:
		assert(!m_bDynamic);	//	reading denied from dynamic buffers
		flags = D3DLOCK_READONLY;
		break;
	}

	HRESULT hr = m_pIB->Lock(offset, size, &m_pLockData, flags);
	assert(hr == D3D_OK);

	return m_pLockData;
}

void CIndexBuffer::Unlock()
{
	m_pLockData = nullptr;

	HRESULT hr = m_pIB->Unlock();
	assert(hr == D3D_OK);
}

uint CIndexBuffer::GetSize() const
{
	return m_length;
}

CIndexBuffer::operator IDirect3DIndexBuffer9* () const
{
	return m_pIB;
}